package org.ztest.thrift;

import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.ztest.thrift.echo.Echo;
import org.ztest.thrift.tutorial.Calculator;

// 阻塞型服务器
public class JavaMultiplexServer2
{
	public static void main(String[] args) throws Exception
	{
		// 复用器
		TMultiplexedProcessor multiplex = new TMultiplexedProcessor();
		
		CalculatorHandler handler1 = new CalculatorHandler();
		Calculator.Processor<CalculatorHandler> processor1 = new Calculator.Processor<CalculatorHandler>(handler1);
		multiplex.registerProcessor("CALCULATOR", processor1);
		
		EchoHandler handler2 = new EchoHandler();
		Echo.Processor<EchoHandler> processor2 = new Echo.Processor<EchoHandler>(handler2);
		multiplex.registerProcessor("ECHO", processor2);
		
		// 阻塞型服务器
		TServerTransport transport = new TServerSocket(9090);
		// 协议需要适配客户端
		TProtocolFactory protocolFactory = new TCompactProtocol.Factory();
		// 1 简单服务器，单线程阻塞
//		TServer.Args arg = new TServer.Args(transport);
//		arg.processor(multiplex);
//		arg.protocolFactory(protocolFactory);
//		TSimpleServer server = new TSimpleServer(arg);
		// 2 线程池服务器，一个连接的io与业务在同一线程完成，线程池驱动多组任务
		TThreadPoolServer.Args arg = new TThreadPoolServer.Args(transport);
		arg.processor(multiplex);
		arg.protocolFactory(protocolFactory);
		// 如果需要异步客户端配合阻塞型服务器使用，只需添加下行代码以使双方协议编解码方式一致即可
		// 异步客户端并不要求服务器是非阻塞或者异步
//		arg.transportFactory(new TFramedTransport.Factory());
		TThreadPoolServer server = new TThreadPoolServer(arg);
		
		server.serve();
	}
}
